<template>

  <!-- 显示加载 -->
  <LoadingCmp :loading="loading" v-if="loading" />


  <div class="container">
    <div class="section">
      <h2>定位城市</h2>
      <div class="location-error" @click="retryLocation">
        <template v-if="currentCity.nm"> {{ currentCity.nm }} </template>
        <template v-else>定位失败，请手动选择城市</template>
      </div>
    </div>

    <div class="section">
      <h2>最近访问城市</h2>
      <div class="cities-list">
        <van-grid :column-num="3" :border="false">
          <van-grid-item v-for="(city, index) in store.historyCities" :key="index">
            <button type="button" class="city-button" @click="setCurrentCity(city)">
              {{ city.nm }}
            </button></van-grid-item>
        </van-grid>
      </div>
    </div>

    <div class="section">
      <h2>热门城市</h2>
      <div class="cities-grid">
        <van-grid :column-num="3" :border="false" v-if="store.hotCities.length > 0">
          <van-grid-item v-for="(hotCity, index) in store.hotCities" :key="index">
            <van-button class="city-button" @click="setCurrentCity(hotCity)">{{
              hotCity
              }}</van-button>
          </van-grid-item>
        </van-grid>
      </div>
    </div>

    <div class="section">
      <van-index-bar v-if="store.allCities.length > 0">
        <template v-for="(Alphabet, index) in uppercaseAlphabet" :key="index">
          <van-index-anchor :index="Alphabet" />
          <template v-for="city in store.allCities" :key="city.id">
            <van-cell :title="city.nm" v-if="city.py.substring(0, 1).toUpperCase() === Alphabet"
              @click="setCurrentCity(city)" />
          </template>
        </template>
      </van-index-bar>
    </div>
  </div>
</template>

<script setup>
import { fetchCitiesList } from '@/api'
import { sortCitiesByPinyin, getCityObjByName } from '@/tools/index.js'
import { ref, onBeforeMount, computed } from 'vue'

import { useRouter } from 'vue-router'
const router = useRouter()

import { useStore } from '@/stores/index.js'
const store = useStore()

const loading = ref(true)

// 使用 computed 来确保 currentCity 是响应式的
const currentCity = computed(() => store.currentCity)

const historyCities = ref([])
const hotCities = ref([])
const allCities = ref([])

const uppercaseAlphabet = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ']

onBeforeMount(async () => {
  loading.value = true
  const res = await fetchCitiesList()
  allCities.value = sortCitiesByPinyin(res.cts) //全部城市
  hotCities.value = res.hot

  store.setHotCities(res.hot)
  store.setAllCities(sortCitiesByPinyin(res.cts))
  loading.value = false
  // console.log("hotCities:", hotCities.value);
  // console.log("allCities:", allCities.value);
})

const retryLocation = () => {
  if (currentCity.value.nm && currentCity.value.nm !== '') {
    //返回首页
    router.push({ path: '/movie' })
  }
}

// 设置当前城市
const setCurrentCity = (city) => {
  if (typeof city === 'object' && city !== null) {
    //设置当前城市
    // console.log('Setting current city:', city) // 添加日志输出
    // currentCity.value = { id: city.id, nm: city.nm }
    store.setCurrentCity({ id: city.id, nm: city.nm })
    //设置最近访问
    store.setHistoryCities({ id: city.id, nm: city.nm })
  } else {
    //设置当前城市
    const cityObj = getCityObjByName(city, allCities.value)
    // console.log('Setting current city:', cityObj) // 添加日志输出
    // currentCity.value = { id: cityObj.id, nm: cityObj.nm }
    store.setCurrentCity({ id: cityObj.id, nm: cityObj.nm })
    //设置最近访问
    store.setHistoryCities({ id: cityObj.id, nm: cityObj.nm })
  }
  // 清空前一个城市的store数据
  store.setMovieList([])
  store.setMovieIds([])
  store.setTotal(0)
  store.setTopRankMovies([])
  store.setTopRankTitle('')

  //根据新城市去加载新的数据
  router.push({ path: '/movie' })
}
</script>

<style scoped>
.container {
  background-color: #ebebeb;
  margin: 0 auto;
  font-size: 14px;
  color: #333;
}

.section {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 10px;
}

.container .section h2 {
  font-size: 14px;
  margin-top: 0;
}

.location-error {
  background-color: #fff;
  color: #333;
  border: 1px solid #fff;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
}

.cities-list,
.cities-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 0px;
  background-color: #fff;
}

.city-button {
  padding: 5px 5px;
  border: none;
  border-radius: 4px;
  background-color: #e9ecef;
  cursor: pointer;
  text-align: center;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
  width: 100px;
}

.city-button:hover {
  background-color: #ced4da;
}

.city-list {
  list-style-type: none;
  padding: 0;
}

.city-list li {
  padding: 10px 0;
  border-bottom: 1px solid #ddd;
}

.city-list li:last-child {
  border-bottom: none;
}

.van-cell {
  cursor: pointer;
}
</style>
